import Axios from 'axios';
import Qs from 'qs';
import store from '../../store';
import router from '../../router';
import { getToken } from './auth';
import Cookies from 'js-cookie';
import util from '@/assets/js/public';
import { Toast } from 'vant';

Axios.defaults.method = 'post';
// TODO 设置超时时间
Axios.defaults.timeout = 60000;
Axios.defaults.headers['Access-Control-Allow-Origin'] = '*';//withCredentials = true;不生效加上这个
Axios.defaults.headers['Access-Control-Allow-Credentials'] = true;//withCredentials = true;不生效加上这个
// Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// Axios.defaults.baseURL = '/'
Axios.defaults.withCredentials = true
// TODO http code 校验
Axios.defaults.validateStatus = function (status) {
	return status
}

// TODO GET 请求 params 序列化
// Axios.defaults.paramsSerializer = function (params) {
//   return Qs.stringify(params)
// }
//service.defaults.baseURL='/api';
// 环境的切换
//if (process.env.NODE_ENV == 'development') {   //开发环境
//    service.defaults.baseURL = process.env.VUE_APP_DEVBASEURL;}
//else if (process.env.NODE_ENV == 'debug') {    //测试环境
//    service.defaults.baseURL = process.env.VUE_APP_DEBBASEURL;
//}
//else if (process.env.NODE_ENV == 'production') {    //生产环境
//    service.defaults.baseURL = process.env.VUE_APP_PROBASEURL;
//}

let isRefreshToken=false,
	promiseArry = [];
//request请求拦截器
Axios.interceptors.request.use(
	config => {
		// if (store.getters.user && store.getters.user.currentCorp) {
		//   config.headers["currentCorp"] = store.getters.user.currentCorp;
		// }
		console.log(getToken())
		if (getToken()) {
			config.headers['Authorization'] = 'Bearer '+getToken();
		}
		if (process.env.VUE_APP_AJAXLOCAL === 'true') {
			config.method = 'get';
			let url = config.url.split('?')[0].split('/');
			//if(typeof config.data ==="string"){
			//if(typeof JSON.parse(config.data)==="object")
			//    config.data=JSON.parse(config.data);
			//else
			//    config.data={"data":config.data};
			//}
			//config.url=`public/ajax/restuumslogin.json`;
			config.data = { url: url, data: config.data };
			config.url = 'api/seller';
		}
		if(config.options){
			config.headers = {
				'Content-Type': 'application/json' //  注意：设置很关键 
			};
		}
		let params=util.getQueryString(config.url);
		params.access_token=getToken();
		// params.Authorization="Bearer "+store.getters.token;
		config.url=util.toUrl(config.url.split('?')[0],params);
		return config;
	},
	error => {
		//console.log("request请求拦截器error",error);
		Promise.reject(error);
	}
);

//respone响应拦截器
Axios.interceptors.response.use(
	response => {
		console.log(response)
		let res = {};
		if (typeof response.data === 'string') {
			if (response.data.indexOf('parent') > -1) res = eval(response.data.replace(new RegExp('parent', 'g'), 'window').split('<script type="text/javascript">')[1].split('</script>')[0]);
			res.errcode = response.status;
		} else {
			if (response.data.type && response.data.type !== 'application/json') {//==='text/xml'  && response.data.type!=="application/json"        
				let filename = response.headers['content-disposition'];
				if (filename) {
					filename = decodeURI(filename.split('filename=')[1]);
					filename = filename.substring(1, filename.length - 1);
					if (filename.indexOf('errcode') > -1) {
						res = { errcode: -1, message: filename.split('-')[1], data: null };
					} else {
						res = { errcode: 0, data: response.data, filename };
					}
				} else {
					res = { errcode: 0, data: response.data, filename };
				}
				res.errcode = response.status;
			} else {
				res = response.data;
				res.errcode = response.status;
			}
		}
		// console.log("响应",JSON.stringify(res));
		// console.log("-----------------------------");
		if (process.env.VUE_APP_AJAXLOCAL === 'true') {
			let resConfig = JSON.parse(response.config.data);
			let url = resConfig.url;
			res = response.data;
			for (var i in url) {
				if (url[i] !== '' && res[url[i]]) {
					res = res[url[i]];
				}
			}
			if (resConfig.data.dictType) res = res[resConfig.data.dictType];
			// console.log(url, res);
		}

		console.log(res)
		if (res.errcode === 0 || res.errcode === 200 || res.access_token) {
			console.log('sss='+res.code);
			if (res.message != undefined && res.message != null && res.message != '' && ((response.config.message==undefined) || response.config.message==true)) {
				// Toast({
				// 	message:res.message,
				// 	duration:1500,
				// 	icon:'success'
				// });
			}
			// console.log("respone响应拦截器success",res);
			return Promise.resolve(res);
		} else {
			if ((res.message != undefined && res.message != null) || res.error_description) {
				Toast({
					message:res.message || res.error_description || '操作失败',
					duration:1500,
					icon:'fail'
				});
			}
			if(res.errcode===401){
				if(!isRefreshToken){
					isRefreshToken=true;
					store.dispatch('SetToken').then((res)=>{
						promiseArry.forEach(item=>item());
						promiseArry=[];
						return Axios(response.config);
					}).catch(error=>{
						isRefreshToken=false;
						return Promise.reject(res);
					});
				}else{
					return new Promise((resolve)=>{
						promiseArry.push(item=>{
							resolve(Axios(response.config));
						})
					})
				}
			}else{
				if (res.errcode === 401 || res.errcode === 302 || res.errcode==404) {
					Toast({
						message:'返回401',
						duration:3000,
						icon:'fail'
					});
					// if (router.history.current.path != '/login') {
					// 	store.dispatch('FedLogOut').then(() => {
					// 		router.push({path:'/login'});
					// 	});
					// }
				}
				// console.log("respone响应拦截器successError",res);
				return Promise.reject(res);
			}
		}
	},
	error => {
		let response = JSON.parse(JSON.stringify(error)).response;
		if (response) {
			if (response.message) {
				Toast({
					message:response.status + '，' + response.message,
					duration:3000,
					icon:'fail'
				});
			}
		
			return Promise.reject(response);
		}
		 else {
			Toast({
				message:'断网啦!?',
				duration:3000,
				icon:'fail'
			});
			console.log('断网啦!?');
		}
	}
);
function request(obj) {
	if (!obj.data) obj.data = {};
	if (((!obj.noCurrent) && ((process.env.VUE_APP_APPCURRENTUSER === undefined) || (process.env.VUE_APP_APPCURRENTUSER != undefined && process.env.VUE_APP_APPCURRENTUSER === 'true'))) && store.getters.user && store.getters.user.currentCorp) {
		obj.data.schoolId = store.getters.user.currentBloc;
		obj.data.zoneId = store.getters.user.currentCorp;
	}
	if (obj.contentType) {
		if (obj.contentType.indexOf('json') > -1) {
			Axios.defaults.headers['Content-Type'] = obj.contentType;
		}
	} else {
		if (obj.data) obj.data = Qs.stringify(obj.data);
		Axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
	}
	// console.log(Axios.defaults.headers["Content-Type"])
	if (!obj.method) obj.method = 'post';

	return new Promise((resolve, reject) => {
		Axios(obj)
			.then(response => {
				resolve(response)
			})
			.catch(error => {
				if (obj.catch) reject(error)
			})
	});
	// if(obj.method && obj.method==='get'){
	//   return new Promise((resolve, reject) => {
	//     Axios.get(obj.url, { params: obj.data,responseType: 'blob'})
	//       .then(response => {
	//         resolve(response)
	//       })
	//       .catch(error => {
	//         reject(error)
	//       })
	//   })
	// }else{
	//   return new Promise((resolve, reject) => {
	//     Axios.post(obj.url, obj.data)
	//       .then(response => {
	//         resolve(response)
	//       })
	//       .catch(error => {
	//         reject(error)
	//       })
	//   })
	// }
	// let ajax;
	// if(obj.method && obj.method==='get'){
	// 	if(obj.responseType)
	// 	ajax=Axios.get(obj.url, { params: obj.data,responseType: 'blob'})
	// 	else
	// 	ajax=Axios.get(obj.url, { params: obj.data})
	// }else{    
	// 	if(obj.responseType)
	// 	ajax=Axios.post(obj.url,obj.data,{responseType: 'blob'});
	// 	else
	// 	ajax=Axios.post(obj.url,obj.data);
	// }
	// return ajax;
};
export default request;
